package com.junzhiit.nengji.api.service.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.bainaeco.framework.util.DateUtil;
import com.junzhiit.nengji.api.service.CommissionHistoryService;
import com.junzhiit.nengji.api.service.IncomeHistoryService;
import com.junzhiit.nengji.api.service.SellSetingService;
import com.junzhiit.nengji.api.web.util.Constants;
import com.junzhiit.nengji.api.web.vo.CommissionHistoryCountVO;
import com.junzhiit.nengji.api.web.vo.CommissionHistoryVO;
import com.junzhiit.nengji.api.web.vo.ListVO;
import com.junzhiit.nengji.api.web.vo.ResultVO;
import com.junzhiit.nengji.bo.CommissionHistoryBO;
import com.junzhiit.nengji.bo.OrdersBO;
import com.junzhiit.nengji.bo.UserVipBO;
import com.junzhiit.nengji.dao.BenefitSettingDAO;
import com.junzhiit.nengji.dao.CommissionHistoryDAO;
import com.junzhiit.nengji.dao.GoodsDataHistoryDAO;
import com.junzhiit.nengji.dao.OrdersDAO;
import com.junzhiit.nengji.dao.OrdersDataHistoryDAO;
import com.junzhiit.nengji.dao.SellLevelDAO;
import com.junzhiit.nengji.dao.SystemConfigDAO;
import com.junzhiit.nengji.dao.UserConfigDAO;
import com.junzhiit.nengji.dao.UserDAO;
import com.junzhiit.nengji.dao.UserVipDAO;
import com.junzhiit.nengji.model.BenefitSetting;
import com.junzhiit.nengji.model.CommissionHistory;
import com.junzhiit.nengji.model.GoodsDataHistory;
import com.junzhiit.nengji.model.OrdersDataHistory;
import com.junzhiit.nengji.model.SellLevel;
import com.junzhiit.nengji.model.SellSeting;
import com.junzhiit.nengji.model.SystemConfig;
import com.junzhiit.nengji.model.User;
import com.junzhiit.nengji.model.UserConfig;
import com.junzhiit.nengji.model.enums.Is;
import com.junzhiit.nengji.model.enums.OrdersDataHistoryStatus;

@Service
public class CommissionHistoryServiceImpl extends BaseServiceImpl implements CommissionHistoryService {

	@Autowired
	private OrdersDAO ordersDAO;
	
	@Autowired
	private UserDAO userDAO;
	
	@Autowired
	private SystemConfigDAO systemConfigDAO;
	
	@Autowired
	private SellLevelDAO sellLevelDAO;
	
	@Autowired
	private BenefitSettingDAO benefitSettingDAO;
	
	@Autowired
	private CommissionHistoryDAO commissionHistoryDAO;
	
	@Autowired
	private UserConfigDAO userConfigDAO;
	
	@Autowired
	private IncomeHistoryService incomeHistoryService;
	
	@Autowired
	private SellSetingService sellSetingService;
	
	@Autowired
	private OrdersDataHistoryDAO ordersDataHistoryDAO;
	
	@Autowired
	private GoodsDataHistoryDAO goodsDataHistoryDAO;
	
	@Autowired
	private UserVipDAO userVipDAO;
	
	@Override
	public void add(String userId, String orderGoodsId,String parentId,String orderDataHistoryId,String goodsDataHistoryId) {
		User user = userDAO.query(userId);
		SystemConfig systemConfig = systemConfigDAO.find();
		SellSeting sellSeting = sellSetingService.findSellSeting();
		if(systemConfig == null && sellSeting == null){
			return;
		}
		int maxLevel = 0;
		if(sellSeting.getIsOpenSell() != null && sellSeting.getIsOpenSell() == Is.YES.toIntValue()){
			maxLevel = sellLevelDAO.getSellLevelMax();
			List<OrdersBO> list = ordersDAO.findOrderByid(orderGoodsId);
			for(OrdersBO orders : list){
				Integer level = 0;
				for (int i = 1; i <=maxLevel; i++) {
					if(StringUtils.isBlank(user.getParentId()) || user.getParentId().equals(Constants.INDUSTRY_ROOT))
						break;
					
					User parentMember = userDAO.query(parentId);
					if(parentMember!=null && StringUtils.isNotBlank(parentMember.getId())){
						parentId = parentMember.getParentId();
						level ++;
					}
				}
				if(level > 0){
					parentId = user.getParentId();
					for (int i = 1; i <=level; i++) {
						if(StringUtils.isBlank(parentId) || parentId.equals(Constants.INDUSTRY_ROOT))
							break;
						User parentUser = userDAO.query(parentId);
						if(parentUser!=null && StringUtils.isNotBlank(parentUser.getId())){
							if(systemConfig.getIsOpenMemberSell() == Is.YES.toIntValue()){
								if(maxLevel == i){
									if(parentUser.getIsMemberSell() != Is.YES.toIntValue()){
										break;
									}
								}
							}
							SellLevel sellLevel = sellLevelDAO.findByLevel(i);
							BenefitSetting benefitSetting = benefitSettingDAO.findBenefit(orders.getProfit());
							if(benefitSetting == null){
								return;
							}
							if(sellLevel!=null && sellLevel.getValue()!=null){
								Double benefitValue = 0.0;
								UserVipBO userVip = userVipDAO.getVipByUserId(userId);
								if(userVip == null){
									benefitValue = benefitSetting.getValue();
								}else{
									if(i == 1){
										benefitValue = userVip.getOneSell();
									}else if(i ==2){
										benefitValue = userVip.getTwoSell();
									}
								}
								Double value = ((orders.getOrderGoodsPayMoney()*orders.getGoodsNumber()) *  benefitValue/100)*sellLevel.getValue()/100;
								CommissionHistory commissionHistory = new CommissionHistory();
								commissionHistory.setIncomeUserId(parentId);
								commissionHistory.setTransactionUserId(user.getId());
								commissionHistory.setCommissionMoney(value);
								commissionHistory.setCommissionLevle(i);
								commissionHistory.setCommissionRation(sellLevel.getValue());
								commissionHistory.setOrderGoodsId(orders.getOrderGoodsId());
								commissionHistory.setOrderNumber(orders.getOrderNumber());
								commissionHistory.setOrderId(orders.getId());
								commissionHistory.setIncomeType(parentUser.getIsShop());
								commissionHistory.setGoodsId(orders.getGoodsId());
								commissionHistory.setGoodsNumber(orders.getGoodsNumber());
								commissionHistory.setGoodsPrice(orders.getPrice());
								commissionHistory.setTransactionType(orders.getType());
								commissionHistory.setEventType(orders.getIsOpenRebate());
								commissionHistory.setPayMoney(orders.getPayMoney());
								commissionHistory.setPsValue(orders.getProfit());
								commissionHistory.setPsRation(benefitSetting.getValue());
								commissionHistoryDAO.insert(commissionHistory);
								
								//更新用户分销金额
								UserConfig userConfig = userConfigDAO.getUserConfig(parentId);
								if(StringUtils.isNoneBlank(userConfig.getId())){
									userConfig.setSellMoney(userConfig.getSellMoney() + value);
									userConfig.setPileSellMoney(userConfig.getPileSellMoney()+value);
									userConfig.setWithdrawalMoney(userConfig.getWithdrawalMoney()+value);
									userConfigDAO.update(userConfig);
								}
								
								//更新资产明细及财务报表
								OrdersDataHistory ordersDataHistory = ordersDataHistoryDAO.query(orderDataHistoryId);
								if(ordersDataHistory != null){
									ordersDataHistory.setShareBenefitMoney(ordersDataHistory.getShareBenefitMoney()+value);
									ordersDataHistory.setStatus(OrdersDataHistoryStatus.COMPLETE.toIntValue());
									ordersDataHistoryDAO.update(ordersDataHistory);
								}
								
								GoodsDataHistory goodsDataHistory = goodsDataHistoryDAO.query(goodsDataHistoryId);
								if(goodsDataHistory != null){
									User parentMember = userDAO.query(parentId);
									if(i == 1){
										goodsDataHistory.setPrimaryBenefitId(parentId);
										goodsDataHistory.setPrimaryBenefitName(parentMember.getNickName());
										goodsDataHistory.setPrimaryBenefitRation(sellLevel.getValue());
										goodsDataHistory.setPrimaryBenefitMoney(value);
									}else if(i == 2){
										goodsDataHistory.setSecondBenefitId(parentId);
										goodsDataHistory.setSecondBenefitName(parentMember.getNickName());
										goodsDataHistory.setSecondBenefitRation(sellLevel.getValue());
										goodsDataHistory.setSecondBenefitMoney(value);
									}
									goodsDataHistoryDAO.update(goodsDataHistory);
								}
								
							}
							parentId = parentUser.getParentId();
						}
					}
				}else{
					//更新资产明细及财务报表
					OrdersDataHistory ordersDataHistory = ordersDataHistoryDAO.query(orderDataHistoryId);
					if(ordersDataHistory != null){
						ordersDataHistory.setStatus(OrdersDataHistoryStatus.COMPLETE.toIntValue());
						ordersDataHistoryDAO.update(ordersDataHistory);
					}
				}
				incomeHistoryService.addIncomeHistory(orders, user.getParentId(),orderDataHistoryId,goodsDataHistoryId);
			}
		}
		
	}

	@Override
	public ResultVO countCommissionHistory(String userId,String startTime, String endTime,int pageNumber, int maxPageRow) {
		ResultVO result = new ResultVO();
		UserConfig userConfig = userConfigDAO.getUserConfig(userId);
		List<CommissionHistoryBO> list = commissionHistoryDAO.countCommissionHistory(userId, startTime, endTime, pageNumber, maxPageRow);
		CommissionHistoryCountVO commissionHistoryCountVO = new CommissionHistoryCountVO();
		for(CommissionHistoryBO params : list){
			CommissionHistoryVO commissionHistoryVO = new CommissionHistoryVO();
			BeanUtils.copyProperties(params, commissionHistoryVO);
			commissionHistoryVO.setCreatedTime(DateUtil.format(params.getCreatedTime()));
			commissionHistoryCountVO.add(commissionHistoryVO);
		}
		commissionHistoryCountVO.setPileSellMoney(userConfig.getPileSellMoney());
		int count = commissionHistoryDAO.getCount(userId, startTime, endTime);
		
		ListVO listVO = new ListVO();
 		listVO.setIndex(pageNumber);
		listVO.setCount(count);
		listVO.setList(commissionHistoryCountVO);
		result.setData(listVO);
		return result;
	}

	
}
